package com.cold.flink;

import com.alibaba.fastjson2.JSON;
import com.cold.common.domain.AlertMessage;
import com.cold.common.domain.DeviceDetails;
import com.cold.common.utils.JedisUtils;
import org.apache.flink.api.common.functions.MapFunction;
import redis.clients.jedis.Jedis;

/**
 * 报警消息实时计算 填充温度和湿度报警属性
 */
public class AlertMessageMap implements MapFunction<AlertMessage,AlertMessage> {

    @Override
    public AlertMessage map(AlertMessage value){
        JedisUtils jedisUtils = JedisUtils.getInstance();
        Jedis jedis = jedisUtils.getJedis();
        try {
            //读取redis中的设备数据
            String json = jedis.get(value.getDeviceCode());
            DeviceDetails device = JSON.parseObject(json, DeviceDetails.class);
            //把设备数据填充到消息中
            value.setAreaName(device.getAreaName());
            value.setCompanyName(device.getCompanyName());
            value.setHostName(device.getHostName());
            value.setMaxHum(device.getMaxHum());
            value.setMinHum(device.getMinHum());
            value.setMaxTem(device.getMaxTem());
            value.setMinTem(device.getMinTem());
            value.setHostType(device.getHostType());
            if(device.getDeviceStatus() == 0){
                value.setDeviceStatus("停用");
            }else if(device.getDeviceStatus() == 1){
                value.setDeviceStatus("正常");
            }else if(device.getDeviceStatus() == -1){
                value.setDeviceStatus("异常");
            }
            //设置温度湿度报警
            if (value.getTem() > value.getMaxTem()) {
                value.setAlertTem(1L);   //高温
            } else if (value.getTem() < value.getMinTem()) {
                value.setAlertTem(-1L);  //低温
            } else {
                value.setAlertTem(0L);   //正常
            }
            if (value.getHum() > value.getMaxHum()) {
                value.setAlertHum(1L);
            } else if (value.getHum() < value.getMinHum()) {
                value.setAlertHum(-1L);
            } else {
                value.setAlertHum(0L);
            }
        } catch (Exception e) {
//            jedisUtils.returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            jedisUtils.returnJedis(jedis);
        }
        System.out.println("转换消息：" + value);
        return value;
    }
}
